const myAxios = function (config) {
  return new Promise((resolve, reject) => {
    const { method, url, data, params } = config
    const xhr = new XMLHttpRequest()
    if (method.toUpperCase() === 'GET') {
      const str = setParams(params)
      xhr.open('GET', params ? url + '?' + str : url)
      xhr.send()
    } else {
      xhr.open('POST', url)

      let flag = Object.prototype.toString.call(data) === '[object Object]'
      xhr.setRequestHeader(
        'Content-Type',
        flag ? 'application/json' : 'application/x-www-form-urlencoded'
      )
      xhr.send(flag ? JSON.stringify(data) : data)
    }

    xhr.onreadystatechange = function () {
      if (xhr.readyState === 4) {
        if (xhr.status >= 200 && xhr.status < 300) {
          resolve(JSON.parse(xhr.responseText))
        } else {
          resolve('请求失败，失败的状态码是' + xhr.status)
        }
      }
    }
  })
}
function setParams(obj) {
  const arr = []
  for (let key in obj) {
    let str = key + '=' + obj[key]
    arr.push(str)
  }
  return str.join('&')
}
